#!/usr/bin/env python
# -*- encoding=utf-8 -*-
'''
Created on 2017/7/5

@author: peulerosci
'''


# need zypper in python-mysql
import MySQLdb
import sys

reload(sys)
sys.setdefaultencoding('utf8')

class db_cve:
    def __init__(self):
        try:
            self.db = MySQLdb.connect('9.41.11.66', 'root', 'root', 'euleros_db', charset = "utf8")
            self.cursor = self.db.cursor()

        except MySQLdb.Error, e:
            print("Mysql Error %d: %s" % (e.args[0], e.args[1]))
    def __del__(self):
        self.db.close()

    def find_by_id(self, table, id_name, id, item):
        sql = "SELECT %s FROM %s WHERE %s='%d'" % (item, table, id_name, id)
        print('DB: ' + sql)
        self.cursor.execute(sql)
        results = self.cursor.fetchall()
        if len(results) == 0:
            return False
        return results[0]

    def find_by_cveid(self, item):
        sql = "SELECT score,v3score,summary FROM tsn_cve WHERE cve_id='%s'" % (item)
        print('DB: ' + sql)
        self.cursor.execute(sql)
        results = self.cursor.fetchall()
        if len(results) == 0:
            return False
        return results[0]

    def update_by_id(self, table, id_name, id, name, value, islogger=True):
        sql = "UPDATE %s SET %s = '%s' WHERE %s = '%d'" % (table, name, value, id_name, id)
        if islogger == True:
            print('DB: ' + sql)
        if value == None:
            sql = "UPDATE %s SET %s = NULL WHERE %s = '%d'" % (table, name, id_name, id)
        try:
            self.cursor.execute(sql)
            # 提交到数据库执行
            self.db.commit()
        except Exception, e:
            # 发生错误时回滚
            self.db.rollback()
            print('%s : %s' % (Exception, e))
            return False

    def find_custom(self, sql):
        print('DB: ' + sql)
        self.cursor.execute(sql)
        results = self.cursor.fetchall()
        return results

    def insert_custom(self, sql):
        print('DB: ' + sql)
        #self.cursor.execute(sql)
        try:
            self.cursor.execute(sql)
            # 提交到数据库执行
            self.db.commit()
        except Exception, e:
            # 发生错误时回滚
            self.db.rollback()
            print('%s : %s' % (Exception, e))
            return False

    def custom(self, sql):
        print('DB: ' + sql)
        # self.cursor.execute(sql)
        try:
            self.cursor.execute(sql)
            # 提交到数据库执行
            self.db.commit()
        except Exception, e:
            # 发生错误时回滚
            self.db.rollback()
            print('%s : %s' % (Exception, e))
            return False
        return True